/* 
 * Copyright (C) 2010 Christian Schneider
 * 
 * This file is part of NS2 news.
 * 
 * NS2 news is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NS2 news is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NS2 news.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package tritop.android.naturalselectionnews;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.ContentValues;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class NewsWorker extends Thread implements IGLOBALS{
	public static final int RSSNEWS=1;
	public static final int TWITTERNEWS=2;
	private static final int CON_TIMEOUT=5*1000;
    private static final String LOGTAG="RSSWorker";
	private URL mUrl;
	private DBHelper mDbHelper;
	private Handler mHandler=null;
	private int mNewsType;
	private int mReturnCode=1;
	//private SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z",Locale.US);  //old RSS Dateformat
	private SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy",Locale.US); //XML Dateformat
	
	NewsWorker(URL url,int newsType,DBHelper dbh,Handler handler){
		this.mUrl = url;
		this.mDbHelper=dbh;
		this.mHandler=handler;
		this.mNewsType=newsType;
	}
	
	@Override
	public void run() {
		switch(mNewsType){
			case RSSNEWS:parseFeed(downloadFeed());break;
			case TWITTERNEWS:/*parseTwitterFeed(downloadFeed());*/parseTwitterXMLFeed(downloadFeed());break;
			default:break;
		}
		
		Message msg=mHandler.obtainMessage(WorkManager.NEWSWORKERMSGID, mReturnCode, 1);
		mHandler.sendMessage(msg);
	}
	
	private String downloadFeed(){
		try {
			StringBuilder sBuilder= new StringBuilder();
			String line=null;
			
			URLConnection con = mUrl.openConnection();
			con.setConnectTimeout(CON_TIMEOUT);
			BufferedReader bReader = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
			
			while((line = bReader.readLine()) !=null){
				sBuilder.append(line);
				if(DEBUG_ON){
					Log.e(LOGTAG,"feed "+line);
				}
			}
			if(sBuilder.toString().startsWith("<?xml")){
				if(DEBUG_ON){
					Log.e(LOGTAG,"valid feed");
				}
				return sBuilder.toString();
			}
			else {return null;}
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	private void parseFeed(String feed){
		if(feed!=null){
			if(DEBUG_ON){
				Log.e(LOGTAG,"parsing");
			}
			try {
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(new StringReader(feed));
				int eventType = xpp.getEventType();
				ContentValues values=null;
				synchronized(mDbHelper){
				mDbHelper.beginBulkWork();
				while(eventType!= XmlPullParser.END_DOCUMENT){
				    if(eventType==XmlPullParser.START_DOCUMENT){
				    	if(DEBUG_ON){
				    		Log.e(LOGTAG,"start doc ");
				    	}
				    }
					if(eventType==XmlPullParser.START_TAG){
						if(DEBUG_ON){
							Log.e(LOGTAG,"start tag "+xpp.getName());
						}
						if(xpp.getName().equalsIgnoreCase("entry")){
							values= new ContentValues();
						}
						else if(values!=null && (xpp.getName().equalsIgnoreCase("title") || xpp.getName().equalsIgnoreCase("link") || xpp.getName().equalsIgnoreCase("updated"))){
							String txt;
							if(xpp.getName().equalsIgnoreCase("link")){
								if(DEBUG_ON){
									Log.e(LOGTAG,"count: "+xpp.getAttributeCount());
								}
								txt=xpp.getAttributeValue("", "href");
							}
							else {
								txt=xpp.nextText();
							}
							if(DEBUG_ON){
								Log.e(LOGTAG,"value pair "+xpp.getName()+" - "+txt);
							}
							values.put(xpp.getName(), txt);
						}
					}
					if(eventType==XmlPullParser.END_TAG){
						if(DEBUG_ON){
							Log.e(LOGTAG,"end tag "+xpp.getName());
						}
						if(xpp.getName().equalsIgnoreCase("entry")){
							if(DEBUG_ON){
								Log.e(LOGTAG,"Saveing");
							}
							mDbHelper.insertNewsFeedValues(values);
						}
					}
					eventType=xpp.nextToken();
				}
				mDbHelper.endBulkWork();
				}
			
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	
	
	//replaced by parseTwitterXMLFeed, requesting same feed in rss  -> Twitter: internal server error...
	private boolean parseTwitterFeed(String feed){
		if(feed!=null){
			if(DEBUG_ON){
				Log.i(LOGTAG,"parsing Twitter");
			}
			try {
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(new StringReader(feed));
				int eventType = xpp.getEventType();
				String title=null;
				long guid=1;
				long date=0;
				synchronized(mDbHelper){
				mDbHelper.beginBulkWork();
				while(eventType!= XmlPullParser.END_DOCUMENT){
				    if(eventType==XmlPullParser.START_DOCUMENT){
				    	if(DEBUG_ON){
				    		Log.i(LOGTAG,"start doc ");
				    	}
				    }
					if(eventType==XmlPullParser.START_TAG){
						if(DEBUG_ON){
							Log.i(LOGTAG,"start tag "+xpp.getName());
						}
						if(xpp.getName().equalsIgnoreCase("item")){
							title=null;
							guid=1;
							date=0;
							mReturnCode=2;
						}
						else if(xpp.getName().equalsIgnoreCase("title")){
							title=xpp.nextText();
						}
						else if(xpp.getName().equalsIgnoreCase("guid")){
							String sguid=xpp.nextText();
							if(DEBUG_ON){
								Log.v(LOGTAG,sguid.substring(sguid.lastIndexOf("/", sguid.length())+1));
							}
							guid=Long.parseLong(sguid.substring(sguid.lastIndexOf("/", sguid.length())+1));
						}
						else if(xpp.getName().equalsIgnoreCase("pubDate")){
							Date dateconv = dateFormat.parse(xpp.nextText());
							date=dateconv.getTime();			
						}
						
					}
					if(eventType==XmlPullParser.END_TAG){
						if(DEBUG_ON){
							Log.i(LOGTAG,"end tag "+xpp.getName());
						}
						if(xpp.getName().equalsIgnoreCase("item")){
							if(DEBUG_ON){
								Log.i(LOGTAG,"Saveing");
							}
							mDbHelper.insertBulkTwitterValues(title,guid,date);
						}
					}
					eventType=xpp.nextToken();
				}
				mDbHelper.endBulkWork();
				}
			
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;	
	}
	
	
	private boolean parseTwitterXMLFeed(String feed){
		if(feed!=null){
			if(DEBUG_ON){
				Log.i(LOGTAG,"parsing Twitter");
			}
			try {
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(new StringReader(feed));
				int eventType = xpp.getEventType();
				String title=null;
				long guid=1;
				long date=0;
				synchronized(mDbHelper){
				mDbHelper.beginBulkWork();
				while(eventType!= XmlPullParser.END_DOCUMENT){
				    if(eventType==XmlPullParser.START_DOCUMENT){
				    	if(DEBUG_ON){
				    		Log.i(LOGTAG,"start doc ");
				    	}
				    }
					if(eventType==XmlPullParser.START_TAG){
						if(DEBUG_ON){
							Log.i(LOGTAG,"start tag "+xpp.getName());
						}
						if(xpp.getName().equalsIgnoreCase("status")){
							title=null;
							guid=1;
							date=0;
							mReturnCode=2;
						}
						else if(xpp.getName().equalsIgnoreCase("text")){
							title=xpp.nextText();
						}
						else if(xpp.getName().equalsIgnoreCase("id") && guid == 1){
							String sguid=xpp.nextText();
							if(DEBUG_ON){
								//Log.v(LOGTAG,sguid.substring(sguid.lastIndexOf("/", sguid.length())+1));
							}
							guid=Long.parseLong(sguid);
						}
						else if(xpp.getName().equalsIgnoreCase("created_at") && date==0){
							Date dateconv = dateFormat.parse(xpp.nextText());
							date=dateconv.getTime();			
						}
						
					}
					if(eventType==XmlPullParser.END_TAG){
						if(DEBUG_ON){
							Log.i(LOGTAG,"end tag "+xpp.getName());
						}
						if(xpp.getName().equalsIgnoreCase("status")){
							if(DEBUG_ON){
								Log.i(LOGTAG,"Saveing "+"date: "+date+" guid:"+guid+" text:"+title);
							}
							mDbHelper.insertBulkTwitterValues(title,guid,date);
						}
					}
					eventType=xpp.nextToken();
				}
				mDbHelper.endBulkWork();
				}
			
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;	
	}
	
	
	
	
}
